import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:hive/hive.dart';
import 'package:meta/meta.dart';

import '../../api/api_client.dart';
import '../../models/user.dart';
import '../../models/user_company.dart';

part 'company_event.dart';
part 'company_state.dart';

class CompanyBloc extends Bloc<CompanyEvent, CompanyState> {
  final ApiClient apiClient;
  late final Box<User> userBox;
  final source = '2'; // 3暂时没数据


  CompanyBloc(this.apiClient) : super(CompanyInitial()) {
    userBox = Hive.box<User>('user_box');
    on<LoadCompanyEvent>(_loadCompany);
    on<DissCompanyEvent>(_deleteCompany);
    on<SetCompanyEvent>(_setCompany);
    on<LoadCompanyVeriEvent>(_cookiesCompany);
    on<CompanyTaxVerificationEvent>(_cookiesVerifyCompany);
    on<CompanyTaxVerifCodeEvent>(_cookiesVerifyVodeCompany);
  }


   int page = 0;
   final int pageSize = 10;
   var oldState = <AppCompanyDto>[];

  @override
  void onChange(Change<CompanyState> change) {
    super.onChange(change);
  }


  FutureOr<void> _setCompany(SetCompanyEvent event, Emitter<CompanyState> emit) async {
    try{
      emit(CompanyLoadState());
      final company = await apiClient.getCompanySwitch(userBox.get('currentUser')?.id ?? '',event?.id ?? '');
      if(company.isSuccessful){
        emit(CompanySetSuccessState(event?.id ?? ''));
      }else{
        emit(CompanyErrorState(company.message ?? '切换失败，请重试'));
      }
    }catch(e){
      print(e);
      emit(CompanyErrorState(e.toString()));
    }
  }


  FutureOr<void> _deleteCompany(DissCompanyEvent event, Emitter<CompanyState> emit) async {
    try{
      emit(CompanyLoadState());
      final company = await apiClient.getCompanyDelete(event?.id ?? '');
      if(company.isSuccessful){
        emit(CompanySetSuccessState(event?.id ?? ''));
        // var value = oldState.firstWhere((element) => element.id == event?.id);
        // oldState.remove(value);
        // emit(CompanySuccessState(oldState));
      }else{
        emit(CompanyErrorState(company.message ?? '删除失败，请重试'));
      }
    }catch(e){
      print(e);
      emit(CompanyErrorState(e.toString()));
    }
  }

  FutureOr<void> _loadCompany(LoadCompanyEvent event, Emitter<CompanyState> emit) async {
    try{
      emit(CompanyLoadState());
      final company = await apiClient.getCompanyList(userBox.get('currentUser')?.id ?? '', page, pageSize);
      var companyData =company.data?.content ?? [];
      if(page == 0){
        oldState =companyData;
        if(companyData.isEmpty){
          emit(CompanyEmptyState());
        }else{
          emit(CompanySuccessState(companyData));
        }
      }else{
        emit(CompanySuccessState([...oldState, ...companyData]));
        oldState = [...oldState, ...companyData];
      }
      if(company.data?.last == true){

      }
      page ++ ;
    }catch(e){
      print(e);
      emit(CompanyErrorState(e.toString()));
    }
  }


  FutureOr<void> _cookiesCompany(LoadCompanyVeriEvent event, Emitter<CompanyState> emit) async {
    try{
      emit(CompanyLoadState());
      final company = await apiClient.cookietaskInfo({'bookName': userBox.get('currentUser')?.appCompanyDto?.name ?? '','source':source});
      if(company.isSuccessful){
        emit(CompanySuccess(company.data ?? {}));
        // var value = oldState.firstWhere((element) => element.id == event?.id);
        // oldState.remove(value);
        // emit(CompanySuccessState(oldState));
      }else{
        emit(CompanyErrorState(company.message ?? '获取失败'));
      }
    }catch(e){
      print(e);
      emit(CompanyErrorState(e.toString()));
    }
  }

  FutureOr<void> _cookiesVerifyCompany(CompanyTaxVerificationEvent event, Emitter<CompanyState> emit) async {
    try{
      emit(CompanyLoadState());
      event.param['source'] = source;
      final company = await apiClient.cookieTaskSave(event.param);
      if(company.isSuccessful || company.code == 201){
        emit(CompanyVerifyDialg(company.code  ?? 201));
      }else{
        emit(CompanyErrorState(company.message ?? '验证失败'));
      }
    }catch(e){
      print(e);
      emit(CompanyErrorState(e.toString()));
    }
  }


  FutureOr<void> _cookiesVerifyVodeCompany(CompanyTaxVerifCodeEvent event, Emitter<CompanyState> emit) async {
    try{
      emit(CompanyLoadState());
      final company = await apiClient.cookieTaskSmsCode(event.param);
      if(company.isSuccessful || company.code == 201){
        emit(CompanyErrorState(company.message ?? '验证码成功'));
        emit(CompanyVerifyCodeSuccessDialg());
      }else{
        emit(CompanyErrorState(company.message ?? '验证失败'));
      }
    }catch(e){
      print(e);
      emit(CompanyErrorState(e.toString()));
    }
  }


}
